package de.stefangoebel.aufgabenplaner;

import java.text.ParseException;
import java.util.Calendar;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.preference.EditTextPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.PreferenceActivity;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class AufgabeActivity extends PreferenceActivity {
	public static final String EDIT_TASK = "EditTask";
	public static final String EDIT_TASK_ID = "EditTaskId";
	public static final String EDIT_TASK_DATE = "EditTaskDate";
	
	private OnPreferenceChangeListener prefChange = new OnPreferenceChangeListener() {
		@Override
		public boolean onPreferenceChange(Preference preference, Object newValue) {
			if (preference instanceof EditTextPreference) {
				preference.setSummary((CharSequence) newValue);
			} else if (preference instanceof ListPreference) {
				preference.setSummary(getTitleFromValue((ListPreference)preference, (String)newValue));
			}
			return true;
		}
	};
	
	private Aufgabe task;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {    
	    super.onCreate(savedInstanceState);
	    addPreferencesFromResource(R.xml.pref_aufgabe);
	    setContentView(R.layout.activity_aufgabe);
	    
		Button button = (Button)findViewById(R.id.button_ok);
		button.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				validateAndSave();
			}
		});
		
		int id = getIntent().getExtras().getInt(EDIT_TASK);
		Calendar date = Misc.getDateFromString(getIntent().getExtras().getString(EDIT_TASK_DATE));
		
		if (id == 0) {
			task = new Aufgabe(this, date);
		} else {
			task = Misc.databaseHandler.readTask(this, id);
		}
		
		TextView txtDate = (TextView)findViewById(R.id.txt_PieChartDate);
		txtDate.setText(DateFormat.getDateFormat(this).format(date.getTime()));
		
		EditTextPreference name = (EditTextPreference) getPreferenceScreen().findPreference("name");
		name.setOnPreferenceChangeListener(prefChange);
		name.setText(task.getName());
		name.setSummary(task.getName());
		
		ListPreference category = (ListPreference) getPreferenceScreen().findPreference("category");
		category.setOnPreferenceChangeListener(prefChange);
		category.setValue(task.getCategory());
		category.setSummary(task.getCategoryText());
		
		ListPreference priority = (ListPreference) getPreferenceScreen().findPreference("priority");
		priority.setOnPreferenceChangeListener(prefChange);
		priority.setValue(task.getPriority());
		priority.setSummary(task.getPriorityText());
		
		ListPreference duration = (ListPreference) getPreferenceScreen().findPreference("duration");
		duration.setOnPreferenceChangeListener(prefChange);
		duration.setValue(String.valueOf(task.getDuration()));
		duration.setSummary(task.getDurationText());
	}
	
	private String getTitleFromValue(ListPreference pref, String value) {
		for(int i = 0; i < pref.getEntryValues().length; i++) {
			if (pref.getEntryValues()[i] == value) {
				return (String)pref.getEntries()[i];
			}
		}
		return null;
	}
	
	private void validateAndSave() {
		int msg = 0;
		
		ListPreference duration = (ListPreference) getPreferenceScreen().findPreference("duration");
		if (duration.getEntry() == null) {
			msg = R.string.pref_aufgabe_alert_duration;
		} else {
			task.setDuration(Integer.parseInt((String)duration.getValue()));
		}
		
		ListPreference priority = (ListPreference) getPreferenceScreen().findPreference("priority");
		if (priority.getEntry() == null) {
			msg = R.string.pref_aufgabe_alert_priority;
		} else {
			task.setPriority((String)priority.getValue());
		}
		
		ListPreference category = (ListPreference) getPreferenceScreen().findPreference("category");
		if (category.getEntry() == null) {
			msg = R.string.pref_aufgabe_alert_category;
		} else {
			task.setCategory((String)category.getValue());
		}
		
		EditTextPreference name = (EditTextPreference) getPreferenceScreen().findPreference("name");
		if (name.getText().isEmpty()) {
			msg = R.string.pref_aufgabe_alert_name;
		} else {
			task.setName(name.getText());
		}
		
		if (msg == 0) {
			Misc.databaseHandler.writeTask(task);
			
			final Intent intent = new Intent();
			intent.putExtra(EDIT_TASK_ID, task.getId());
			setResult(Activity.RESULT_OK, intent);
			
			finish();
		} else {
			AlertDialog alertDialog = new AlertDialog.Builder(AufgabeActivity.this).create();
			alertDialog.setTitle(R.string.pref_aufgabe_alert_title);
			alertDialog.setMessage(getString(msg));
			alertDialog.setButton(getString(android.R.string.ok), new DialogInterface.OnClickListener() {
		        public void onClick(DialogInterface dialog, int id) {
		            dialog.cancel();
		        }
		    });
			alertDialog.show();
		}		
	}

}
